﻿using CleanArchitecture.Core.Configuration;
using CleanArchitecture.Core.Events;
using CleanArchitecture.Core.Handlers;
using CleanArchitecture.Core.Interfaces;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Entities.Business;
using CleanArchitecture.Infrastructure.Interfaces;
using CleanArchitecture.Infrastructure.Interfaces.Business;
using System;
using System.Linq;

namespace CleanArchitecture.Infrastructure.Services.Business
{
    public partial class AdvertiseService : IAdvertiseService
    {
        #region Fields
        private readonly IDomainEventDispatcher _eventDispatcher;
        private readonly IRepository<Advertise> _advertiseRepository;
        #endregion

        #region Ctor
        public AdvertiseService(IDomainEventDispatcher eventDispatcher,
            IRepository<Advertise> advertiseRepo)
        {
            this._eventDispatcher = eventDispatcher;
            this._advertiseRepository = advertiseRepo;
        }
        #endregion

        /// <summary>
        /// Gets all AdvertiseBanner Items by page 
        /// </summary>
        /// <returns></returns>
        public IViewPagedList<Advertise> GetAdvertiseBannerItemsByPage(int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var query = _advertiseRepository.TableNoTracking;
            query = query.Where(n => n.IsActive == EntityEnumConfig.YesorNo.YES)
                         .OrderBy(n => n.DisplayOrder);

            var advs = new ViewPagedList<Advertise>(query, pageIndex, pageSize);
            return advs;
        }

        public Advertise GetAdvertiseEntityById(int entityId)
        {
            if (entityId == 0) return null;
            return _advertiseRepository.GetById(entityId);
        }

        public void UpdateAdvertise(Advertise entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            _advertiseRepository.Update(entity, new string[] { nameof(entity.CreatedOnTimeUtc) });
            //event notification
            if (!string.IsNullOrEmpty(entity.SysLogMsg))
                _eventDispatcher.Dispatch(new EntityUpdatedEvent<Advertise>(entity));
        }

        public void InsertAdvertise(Advertise entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            _advertiseRepository.Insert(entity);
            //event notification
            if (!string.IsNullOrEmpty(entity.SysLogMsg))
                _eventDispatcher.Dispatch(new EntityInsertedEvent<Advertise>(entity));
        }

        public void DeleteAdvertise(Advertise entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));
            entity.AdvBannerName = entity.AdvBannerName + "-Deleted";
            entity.IsActive = EntityEnumConfig.YesorNo.No;
            this.UpdateAdvertise(entity);
        }
    }
}
